from asyncio.queues import Queue
from lib import singleton
import g
import traceback


@singleton
class ModelLogQueue(object):
    def __init__(self):
        self.queue = Queue()

    async def run(self):
        """写mongo"""
        while True:
            model_log = await self.queue.get()
            mdb = g.mdb if model_log.pop("ver") == "local" else g.cross_mdb

            act, db_name, data_list = model_log["act"], model_log["db_name"], model_log["data_list"]
            _err, _writeErr = None, None
            try:
                await getattr(mdb, act)(db_name, *data_list)
            except Exception as e:
                err, _writeErr = str(traceback.format_exc()), e
                print(f"ModelLogQueue run error->{err}")

            # await mdb.insert_one("model_log", model_log)

    def put(self, model_log):
        self.queue.put_nowait(model_log)
